﻿using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AyFrame.DbEntity;
using AyFrame.DbEntity.Models;
using AyFrame.Dto;
using AyFrame.NSerialLog;

namespace AyFrame.Services
{
    public class BaseService<T> : Repository<T> where T : BaseEntity, new()
    {
        protected ISqlSugarClient unitOfWork { get; init; }

        public BaseService() : base(DbScoped.Sugar)
        {
            unitOfWork = DbScoped.Sugar;
        }

        protected async Task<UserInfo> GetUser(string userId)
        {
            var user = await unitOfWork.Queryable<SysUserInfo>()
                .Where(t => t.Id == userId)
                .FirstAsync();

            if (user == null) throw new Exception("用户不存在");

            return new UserInfo
            {
                Name = user.Name,
                Uid = user.Uid
            };
        }

        #region 数据增改删
        protected async Task<T> GetUpdateEntity(string id, string timeStamp)
        {
            var entity = await GetSingleAsync(t => t.Id == id);
            if (entity == null) throw new Exception($"未找到【{id}】");
            if (entity.TimeStamp != timeStamp) throw new Exception("已被其他操作修改，当前修改失败");

            return entity;
        }

        protected async Task<int> InsertData(UserInfo curUser, T entity)
        {
            return await AsInsertable(entity)
                    .EnableDiffLogEvent(new { uid = curUser.Uid })
                    .ExecuteCommandAsync();
        }

        protected async Task<int> UpdateData(UserInfo curUser, T entity)
        {
            entity.TimeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            return await AsUpdateable(entity)
                    .EnableDiffLogEvent(new { uid = curUser.Uid })
                    .ExecuteCommandAsync();
        }

        protected async Task<int> DeleteDataL(UserInfo curUser, List<T> entiies)
        {
            return await AsUpdateable(entiies)
                .EnableDiffLogEvent(new { uid = curUser.Uid })
                .ExecuteCommandAsync();
        }

        protected void DeleteDataP(UserInfo curUser, List<T> entiies)
        {
            entiies.ForEach(async t => await DeleteAsync(t));
        }

        protected void UseTrans(Action action)
        {
            try
            {
                unitOfWork.Ado.BeginTran();
                action();
                unitOfWork.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                unitOfWork.Ado.RollbackTran();
                LogHelper.LogError("事务异常", ex);
                throw;
            }
        }
        #endregion
    }
}
